package com.htfyun.factorytest.config;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;

import com.htfyun.factorytest.RootApplication;
import com.htfyun.factorytest.device.DeviceAttr;
import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.ShellUtils;
import com.htfyun.factorytest.utils.SystemPropertyUtil;

/**
 * Created by sst on 2018/7/25.
 */

public final class EinkProperty {

    private static final String TRUE = "true";
    private static final String FALSE = "false";

    /**
     * 该 property 将屏蔽掉按键功能.
     * let app handle every key while in eink factory test
     */
    private static final String EINK_FACTORY_TEST = "sys.eink.factorytest";
//    private static final String EINK_FACTORY_TEST = "persist.eink.factorytest";

    public static void setEinkFactoryTestEnabled(boolean enabled) {
        SystemPropertyUtil.setSystemProperty(EINK_FACTORY_TEST, enabled ? "1" : "0");
    }

    /**
     * pc 需要这个 persist 来判断 PCBA 是否测试ok
     */
    private static final String EINK_PCBA_TEST = "persist.sys.pcba.result";

    public static void setEinkPCBATestAllResultPassed(boolean passed) {
        SystemPropertyUtil.setSystemProperty(EINK_PCBA_TEST, passed ? TRUE : FALSE);
    }

    /**
     * pc 需要这个 persist 来判断 FT 是否测试ok
     */
    private static final String EINK_FT_TEST_ALL_RESULT = "persist.sys.ft.result";

    public static void setEinkFTTestAllResultPassed(boolean passed) {
        SystemPropertyUtil.setSystemProperty(EINK_FT_TEST_ALL_RESULT, passed ? TRUE : FALSE);
    }

    /**
     * 当这个为true时, 不再启动 此 apk.
     */
    private static final String EINK_PV_RO_EINKFT_DONE = "pv.ro.einkft.done";

    public static boolean isPvRoEinkFTDone() {
        ShellUtils.CommandResult result = ShellUtils.execCommand("privdata -p " + EINK_PV_RO_EINKFT_DONE, false);
        DebugLog.d("result = " + result);
        if (result.result == 0 && !TextUtils.isEmpty(result.errorMsg)) {
            try {
                final String done = result.errorMsg.substring(result.errorMsg.indexOf("=") + 1)/*SystemPropertyUtil.getSystemProperty(EINK_PV_RO_EINKFT_DONE)*/;
                return TRUE.equalsIgnoreCase(done);
            } catch (IndexOutOfBoundsException e) {
                DebugLog.e(e.getMessage());
            }
        } else {
            DebugLog.e("read pv error, return done false");
            return false;
        }
        return false;
    }

    //    private static final String EINK_CUSTOMER = "ro.sys.customer";
    private static final String EINK_CUSTOMER = "ro.sys.project"; //PX30,jz97

    public static String getDeviceCustomer() {
        String customer = SystemPropertyUtil.getSystemProperty(EINK_CUSTOMER);
        if (TextUtils.isEmpty(customer)) {
            customer = "iflytekT2";
        }
        return customer;
    }

    public static boolean isSuper() {
        return getDeviceCustomer().contains("super");
    }

    public static boolean isR2() {
        return DeviceAttr.iflytekR2.name().equals(getDeviceCustomer());
    }

    public static boolean isPan6() {
        return DeviceAttr.Pan6.name().equals(getDeviceCustomer());
    }

    public static boolean isJyt() {
        return DeviceAttr.jyt103s.name().equalsIgnoreCase(getDeviceCustomer());
    }

    public static boolean isAoyi60s() {
        return DeviceAttr.Aoyi60s.name().equals(getDeviceCustomer());
    }

    public static boolean isDualScreenOrDualSql() {
        return isDualScreen() || isDualSgl();
    }

    public static boolean isDualScreen() {
        return DeviceAttr.dual103h.name().equals(getDeviceCustomer())
                || DeviceAttr.dualtc.name().equals(getDeviceCustomer())
                || DeviceAttr.dual103hv2.name().equals(getDeviceCustomer())
                || DeviceAttr.dualdz.name().equals(getDeviceCustomer());
    }

    public static boolean isDualSgl() {
        return DeviceAttr.dualsgl.name().equals(getDeviceCustomer());
    }
//    //android bug collection
//    private static final String ABC_SWITCH = "persist.sys.abc_switch";
//    public static void setAbcSwitchEnabled() {
//
//        SystemPropertyUtil.setSystemProperty(ABC_SWITCH, "1");
//
//    }

    /**
     * persist.sys.boot.count > 1 是异常重启的错误。
     */
    private static final String ERROR_BOOT_COUNT = "persist.sys.boot.count";
    private static final String ERROR_BOOT_NEED_TEST = "persist.sys.boot.count_need_test";

    public static int getErrorBootCount() {

        String errorBootCntString = SystemPropertyUtil.getSystemProperty(ERROR_BOOT_COUNT);
        if (TextUtils.isEmpty(errorBootCntString)) {
            return 0;
        }
        if (!TextUtils.isDigitsOnly(errorBootCntString)) {
            DebugLog.e("errorBootCntString is not digit, which is " + errorBootCntString);
            return 0;
        }

        return Integer.parseInt(errorBootCntString) - 1;
    }

    public static void clearErrorBootCount() {
        SystemPropertyUtil.setSystemProperty(ERROR_BOOT_COUNT, "1");
    }

    public static boolean isErrorBootCount() {
        String countNeedTestString = SystemPropertyUtil.getSystemProperty(ERROR_BOOT_NEED_TEST);
        if (TextUtils.isEmpty(countNeedTestString)) {
            return false;
        }

        if (!TextUtils.isDigitsOnly(countNeedTestString)) {
            return false;
        }

        int need = Integer.parseInt(countNeedTestString);
        if (need > 0) {
            return getErrorBootCount() > 0;
        }

        return false;
    }

    /**
     * 启动 cpuTest service 且判断 "persist.sys.cputest.result" 属性：starting, ok, fail.
     * 启动服务可以通过设置属性：setprop  ctl.start cpuTest
     * 停止服务可以通过设置属性: setprop  ctl.stop cpuTest
     */
    public enum CpuTestResultAttr {
        running0("running0"),
        running1("running1"),
        ok("ok"),
        fail("fail");
        private final String result;

        CpuTestResultAttr(String result) {
            this.result = result;
        }

        public String getResult() {
            return result;
        }
    }

    private static final String RESULT_CPU_TEST = "persist.sys.cputest.result";

    public static String getResultCpuTest() {
        return SystemPropertyUtil.getSystemProperty(RESULT_CPU_TEST);
    }

    public static CpuTestResultAttr getCpuTestResultAttr() {
        CpuTestResultAttr attr = CpuTestResultAttr.running0;

        String result = getResultCpuTest();

//        DebugLog.e("cpuTest: getCpuTestResult = " + result);

        for (CpuTestResultAttr resultAttr : CpuTestResultAttr.values()) {
            if (result.equalsIgnoreCase(resultAttr.getResult())) {
                attr = resultAttr;
            }
        }

        return attr;
    }

    public static void clearCpuTestResult() {
        SystemPropertyUtil.setSystemProperty(RESULT_CPU_TEST, CpuTestResultAttr.ok.getResult());
    }

    private static boolean isCpuTestStarted = false;

    public static void startOrStopCpuTest(boolean start) {
        final String value = "cpuTest";
        final String propNameStart = "ctl.start";
        final String propNameStop = "ctl.stop";

        if (isCpuTestStarted && start) {
            return;
        }
        isCpuTestStarted = start;

        if (start) {
            SystemPropertyUtil.setSystemProperty(propNameStart, value);
            DebugLog.e("songshitian cpuTest: start Cpu Test");
        } else {
            SystemPropertyUtil.setSystemProperty(propNameStop, value);
            DebugLog.e("songshitian cpuTest: stop Cpu Test");
        }
    }

    //通过 "sys.cputest.memsize" 256 来设置memtest的大小，单位是 M。
    private static final String SET_CPUTEST_MEMSIZE = "sys.cputest.memsize";

    public static void setCpuTestMemsize(int size_m) {
        SystemPropertyUtil.setSystemProperty(SET_CPUTEST_MEMSIZE, String.valueOf(size_m));
    }

    private static final String SET_CPUTEST_MEMTIME = "sys.cputest.memtime";

    public static void setCpuTestMemTime(long time_second) {
        SystemPropertyUtil.setSystemProperty(SET_CPUTEST_MEMTIME, String.valueOf(time_second));
    }

    public static void enterBootloader() {
        String cmd = "sys.powerctl";
        String value = "reboot,loader";
        SystemPropertyUtil.setSystemProperty(cmd, value);
    }

    /**
     * ro.sys.mem.size=1.8 \
     * ro.sys.emmc.size=28 \
     */
    private static final String MEM_SIZE = "ro.sys.mem.size";
    private static final String EMMC_SIZE = "ro.sys.emmc.size";

    public static float getRamSize() {
        String size = SystemPropertyUtil.getSystemProperty(MEM_SIZE);
        if (TextUtils.isEmpty(size)) {
            return -1.0f;
        }

        try {
            return Float.parseFloat(size);
        } catch (Exception e) {
            return -1.0f;
        }
    }

    public static float getRomSize() {
        String size = SystemPropertyUtil.getSystemProperty(EMMC_SIZE);
        if (TextUtils.isEmpty(size)) {
            return -1.0f;
        }

        try {
            return Float.parseFloat(size);
        } catch (Exception e) {
            return -1.0f;
        }
    }

    /**
     * 如果 tcon 没有连接上, 那么 led 灯就需要闪烁, 3 长 2 短.
     */
    private static final String TCON_STATUS = "sys.display.tcon.status";

    //property_set("sys.display.tcon.status", stus.connected?"connected":"disconnected");
    public static boolean isTCONConnected() {
        String status = SystemPropertyUtil.getSystemProperty(TCON_STATUS);
        if (TextUtils.isEmpty(status)) {
            return true;
        }
        return status.equalsIgnoreCase("connected");
    }

    //产品版本
    private static final String PRODUCT_VERSION = "ro.product.version";

    public static String getProductVersion() {
//        String version = SystemPropertyUtil.getSystemProperty(PRODUCT_VERSION);
        String version = Build.VERSION.INCREMENTAL;
        if (TextUtils.isEmpty(version)) {
            return "";
        }
        return version;
    }

    //产品序列号
    private static final String SERIAL_NUMBER = "ro.serialno";

    public static String getSerialNumber() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                && ActivityCompat.checkSelfPermission(
                RootApplication.getContext(),
                Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            return Build.getSerial();
        } else {
            String version = SystemPropertyUtil.getSystemProperty(SERIAL_NUMBER);
            if (TextUtils.isEmpty(version)) {
                return "";
            }
            return version;
        }

    }

    // 老化时是否刷屏
    private static final String AGING_UPDATE_SCREEN_ENABLED = "persist.htfyun.aging_screen";

    public static boolean isAgingScreen() {
        String enabled = SystemPropertyUtil.getSystemProperty(AGING_UPDATE_SCREEN_ENABLED);
        if (TextUtils.isEmpty(enabled)) {
            return true;
        }
        return "1".equals(enabled) || "true".equalsIgnoreCase(enabled);
    }

    // 板子硬件音频解析方式
    /**
     * 使用属性 "persist.iflytek.board_version"
     * 属性返回值是int型，分别表示：
     * 值为0：T2版本的时候, i2s is master, codec is slave, and xfm10213 is connected to codec, no bt
     * 值为1：量产版本: i2s is master, codec is slave, and xfm10213/bt is connected to codec
     * 值为2：直通版本XFM10213: i2s and codec are both slave, and xfm10213 is connected to cpu, bt to codec;
     * 值为3：直通版本ES7210:i2s and codec are both slave, and es7210 is connected to cpu, bt to codec;
     * 当有ES7210时，获取"persist.pcm_32bit.enabled"属性的值为”1”;
     */
    private static final String IFLYTEK_BOARD_VERSION = "persist.iflytek.board_version";
    private static final String IFLYTEK__VERSION = "ro.sys.project";

    private static int getIflytekBoardVersion() {
        String versionString = SystemPropertyUtil.getSystemProperty(IFLYTEK_BOARD_VERSION);
        if (TextUtils.isEmpty(versionString) || !TextUtils.isDigitsOnly(versionString)) {
            return -1;
        }
        return Integer.decode(versionString);
    }

    private static boolean getIflytekVersion() {
        String versionString = SystemPropertyUtil.getSystemProperty(IFLYTEK__VERSION);
/*        if (TextUtils.equals(versionString, "iflytekR2")) {
            return false;
        }*/
        return TextUtils.isEmpty(versionString) || versionString.contains("iflytek");
    }

    public static boolean isES7210Record() {
        return true;
//        return getIflytekVersion();
//        return getIflytekBoardVersion() == 3;
    }

    /**
     * px30(rk3326) 读取 rom 时,他是mmcblk1, 而不是常规的mmcblk0
     *
     * @return
     */
    public static boolean isRK3326Platform() {
        String platform = SystemPropertyUtil.getSystemProperty("ro.board.platform");
        return platform.equalsIgnoreCase("rk3326");
    }

}
